﻿namespace ChessToys
{
    using System.Collections.Generic;

    /// <summary>
    /// Utilities for proving a given <see cref="Board"/> for check or checkmate.
    /// </summary>
    public static class CheckUtils
    {
        /// <summary>
        /// Determines whether the specified board is check for the color.
        /// </summary>
        /// <param name="board">The board.</param>
        /// <param name="color">The color.</param>
        /// <returns>
        /// 	<c>true</c> if the specified board is check for the color; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsCheck(Board board, Color color)
        {
            // get the position of the king to prove
            Position kingPosition = GetKingPosition(board, color);
            // get all possible moves for oponents color
            ISet<Move> moves = MoveGeneratorUtils.PossibleMoves(board, color.Toggle());
            // verify for each move if its end points to the kings position -> check
            foreach (Move move in moves)
            {
                if (move.End == kingPosition)
                {
                    return true;
                }
            }
            // no oponents piece gives check
            return false;
        }

        private static Position GetKingPosition(Board board, Color color)
        {
            foreach (Position position in board)
            {
                IPiece piece = board[position];
                if (piece != null && PieceUtils.Is(piece, typeof(King), color))
                {
                    return position;
                }
            }
            return null;
        }

        /// <summary>
        /// Determines whether the specified board is checkmate for the color.
        /// </summary>
        /// <param name="board">The board.</param>
        /// <param name="color">The color.</param>
        /// <returns>
        /// 	<c>true</c> if the specified board is checkmate for the color; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsCheckMate(Board board, Color color)
        {
            // get all possible moves
            ISet<Move> moves = MoveGeneratorUtils.PossibleMoves(board, color);
            // if no more move is possible -> checkmate
            return moves.Count == 0;
        }
    }
}
